<?php
/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * CURL请求
 * @param $url 请求url地址
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

/**
 * 过滤数组元素前后空格 (支持多维数组)
 * @param $array 要过滤的数组
 * @return array|string
 */
function trim_array_element($array){
    if(!is_array($array))
        return trim($array);
    return array_map('trim_array_element',$array);
}

function urlsafe_b64encode($string)
{
    $data = base64_encode($string);
    $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    return $data;

}

function t(){
    echo 1334;
}

/**
 * 对象 转 数组
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
    return $obj;
}

/**
 * 数组转对象
 * @param array $arr
 */
function array_to_Object($arr){
    if(is_array($arr)){
        return (object) array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}
/**
 * 检测会员
 * @param bool|false $is_encryption
 * @return array
 */
function checkMember($member_id){
    if($member_id < 1) return false;
    $where = array('id' => $member_id,'status'=>1);
    $member = db('member')->where($where)->find();
    if(empty($member)) return false;
    if($member['status'] == 0) return false;
    return $member;
}

/**
 * 添加图片URL
 * @param bool|false $is_encryption
 * @return array
 */
function getImageUrl($root,$value)
{
    if(!empty($value)) return __ROOT__ . '/static/'.$root .'/'.str_replace('\\',"/",$value);
}
/**
 * 添加图片URL
 * @param bool|false $is_encryption
 * @return array
 */
function getUploadsUrl($value)
{
    if(!empty($value)) return __ROOT__ . '/static/uploads/'.str_replace('\\',"/",$value);
}

/**
 * 搜数据库多条
 * 
 */
function getSelect($model,$field,$where)
{
    $select = db($model)->where("$field=$where")->select();
	return $select;
}
/**
 * 搜数据库单条
 * 
 */
function getInfo($model,$field,$where)
{
    $find = db($model)->where("id=$where")->column($field);
	if(!empty($find)){
		return $find[0];
	}else{
		return '';
	}
	
}

/**
 * 模型所有对象数据转数组
 * @param object $obj
 */
function modelObjectToArray($obj){
    if(empty($obj)) return array();
    $data = array();
    foreach($obj as $g){
        $data[] = $g->toArray();
    }
    return $data;
}
/**
 * 截取字符串
 * 
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
        $slice= mb_substr($str, $start, $length, $charset);
    }elseif(function_exists('iconv_substr')) {
        $slice= iconv_substr($str,$start,$length,$charset);
    }else{
        $re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
        $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
        $re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
        $re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("",array_slice($match[0], $start, $length));
    }    
        $fix='';
        if(strlen($slice) < strlen($str)){
            $fix='';
        }
        return $suffix ? $slice.$fix : $slice;
}

/**
*判断是否是手机端还是PC端
*/
function is_mobile(){
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
  if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
    return true;
  } 
  // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
  if (isset($_SERVER['HTTP_VIA'])) { 
    // 找不到为flase,否则为true
    return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
  } 
  // 脑残法，判断手机发送的客户端标志,兼容性有待提高。其中'MicroMessenger'是电脑微信
  if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $clientkeywords = array('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile','MicroMessenger'); 
    // 从HTTP_USER_AGENT中查找手机浏览器的关键字
    if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
      return true;
    } 
  } 
  // 协议法，因为有可能不准确，放到最后判断
  if (isset ($_SERVER['HTTP_ACCEPT'])) { 
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
    if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
      return true;
    } 
  } 
  return false;
}

//添加权限 公式公告,通知公告,政策文件
function infinite_notice_policy($data, $string){
    if(empty($string))return false;

    $jurisdiction = array();

    //公式公告,通知公告,政策文件
    $result = unserialize($data[$string]);
    if($result[''.$string.'_condition'] == '1'){

        //有限条件
        $jurisdiction[$string]['is_condition'] = '1';

        //是否查阅
        if($result[''.$string.'_consult'] == '1')
        {
            //可查询
            $jurisdiction[$string][''.$string.'_consult']['is_consult'] = '1';
        }else{
            //不可查询
            $jurisdiction[$string][''.$string.'_consult']['is_consult'] = '-1';
        }

        //查阅是否无限或者有限
        if($result[''.$string.'_consult_num'] == '-2')
        {   
            $jurisdiction[$string][''.$string.'_consult']['is_infinite'] = '1';
            $jurisdiction[$string][''.$string.'_consult']['num'] = '0';
        }else{
            $jurisdiction[$string][''.$string.'_consult']['is_infinite'] = '-1';
            $jurisdiction[$string][''.$string.'_consult']['num'] = $result[''.$string.'_consult_num'];
        }

        //是否预览
        if($result[''.$string.'_enclosure'] == '1')
        {
            //可查询
            $jurisdiction[$string][''.$string.'_enclosure']['is_enclosure'] = '1';
        }else{
            //不可查询
            $jurisdiction[$string][''.$string.'_enclosure']['is_enclosure'] = '-1';
        }

        //查阅是否无限或者有限
        if($result[''.$string.'_enclosure_num'] == '-2')
        {
            $jurisdiction[$string][''.$string.'_enclosure']['is_infinite'] = '1';
            $jurisdiction[$string][''.$string.'_enclosure']['num'] = '0';
        }else{
            $jurisdiction[$string][''.$string.'_enclosure']['is_infinite'] = '-1';
            $jurisdiction[$string][''.$string.'_enclosure']['num'] = $result[''.$string.'_enclosure_num'];
        }

        //是否可下载
        if($result[''.$string.'_down'] == '1')
        {
            //可下载
            $jurisdiction[$string][''.$string.'_down']['is_down'] = '1';

        }else{
            //不可下载
            $jurisdiction[$string][''.$string.'_down']['is_down'] = '-1';
        }

        //查阅是否无限或者有限
        if($result[''.$string.'_down_num'] == '-2')
        {
            $jurisdiction[$string][''.$string.'_down']['is_infinite'] = '1';
            $jurisdiction[$string][''.$string.'_down']['num'] = '0';
        }else{
            $jurisdiction[$string][''.$string.'_down']['is_infinite'] = '-1';
            $jurisdiction[$string][''.$string.'_down']['num'] = $result[''.$string.'_down_num'];
        } 
    }else{
        //无限条件
        $jurisdiction[$string]['is_condition'] = '0';
        //可查询
        $jurisdiction[$string][''.$string.'_consult']['is_consult'] = '1';
        $jurisdiction[$string][''.$string.'_consult']['is_infinite'] = '1';
        $jurisdiction[$string][''.$string.'_consult']['num'] = '0';
        //可查询
        $jurisdiction[$string][''.$string.'_enclosure']['is_enclosure'] = '1';
        $jurisdiction[$string][''.$string.'_enclosure']['is_infinite'] = '1';
        $jurisdiction[$string][''.$string.'_enclosure']['num'] = '0';
        //可下载
        $jurisdiction[$string][''.$string.'_down']['is_down'] = '1';
        $jurisdiction[$string][''.$string.'_down']['is_infinite'] = '1';
        $jurisdiction[$string][''.$string.'_down']['num'] = '0';
    }

    return $jurisdiction;
}

//添加权限 条件查询
function user_jurisdiction($data, $string){
    if(!isset($data))return false;
    if(!is_array($data))return false;
    if(!isset($data[$string]))return false;

    $jurisdiction = array();

    if($data[$string] == '-1'){
        $jurisdiction[$string]['is_condition'] = '-1';
    }else{
        $jurisdiction[$string]['is_condition'] = '1';
    }

    //是否无限
    if($data[$string] != '-2'){
        $jurisdiction[$string]['is_infinite'] = '-1';

        if($data[$string] == '-1'){
            $jurisdiction[$string]['num'] = '0';
        }else{
            $jurisdiction[$string]['num'] = $data[$string];
        }
    }else{
        $jurisdiction[$string]['is_infinite'] = '1';
        $jurisdiction[$string]['num'] = '0';
    }

    return $jurisdiction;
}

//修改权限 公式公告,通知公告,政策文件
function edit_infinite_notice_policy($data, $string, $string_type = '', $result){
    if(!isset($result[$string]))return $data;

    if($data[$string]['is_condition'] != $result[$string]['is_condition']){
        $data[$string]['is_condition'] = $result[$string]['is_condition'];
    }

    if(isset($result[$string][''.$string.'_'.$string_type.''])){
        if($result[$string][''.$string.'_'.$string_type.'']['is_'.$string_type.''] != $data[$string][''.$string.'_'.$string_type.'']['is_'.$string_type.'']){
            $data[$string][''.$string.'_'.$string_type.'']['is_'.$string_type.''] = $result[$string][''.$string.'_'.$string_type.'']['is_'.$string_type.''];
        }

        if($result[$string][''.$string.'_'.$string_type.'']['num'] == '-2'){
            $data[$string][''.$string.'_'.$string_type.'']['is_infinite'] = '1';
            $data[$string][''.$string.'_'.$string_type.'']['num'] = '0';
        }

        if($result[$string][''.$string.'_'.$string_type.'']['num'] > 0){
            $data[$string][''.$string.'_'.$string_type.'']['is_infinite'] = '-1';
            $data[$string][''.$string.'_'.$string_type.'']['num'] = $result[$string][''.$string.'_'.$string_type.'']['num'];
        }
    }

    return $data;
}

//修改权限 条件查询
function user_edit_jurisdiction($data, $string, $result){
    if(!is_array($data))return $data;
    if(!isset($data[$string]))return $data;

    //是否允许
    if($result == '-1'){
        $data[$string]['is_condition'] = '-1';
    }else{
        $data[$string]['is_condition'] = '1';
    }

    //无限
    if($result == '-2'){
        $data[$string]['is_infinite'] = '1';
        $data[$string]['num'] = '0';
    }

    //有限
    if($result != '-1' && $result != '-2' && $result>0){
        $data[$string]['is_infinite'] = '-1';
        $data[$string]['num'] = $result;
    }

    return $data;
}

//用户权限写入,用于注册与套餐改变的时候
function user_input($uid, $type_id){
    $member_result = db('member')->where(array('id'=>$uid))->find();
    if(empty($member_result))return false;
    $member_authority_result = db('member_authority')->where(array('id'=>$type_id))->find();
    if(empty($member_authority_result))return false;

    $jurisdiction = array();

    //项目查询
    $jurisdiction = array_merge(user_jurisdiction($member_authority_result, 'project'),infinite_notice_policy($member_authority_result, 'formula'),infinite_notice_policy($member_authority_result, 'circular'),infinite_notice_policy($member_authority_result, 'policy'),user_jurisdiction($member_authority_result, 'enterprise_follow_num'),user_jurisdiction($member_authority_result, 'wechat_tweets_num'),user_jurisdiction($member_authority_result, 'policy_interpretation_num'),user_jurisdiction($member_authority_result, 'tracking_bulletin_num'),user_jurisdiction($member_authority_result, 'enterprise_planning_num'));
    
    $jurisdiction['business_doctor'] = $member_authority_result['business_doctor'];
    $jurisdiction['information_maintenance'] = $member_authority_result['information_maintenance'];

    $data['num'] = serialize($jurisdiction);
    
    if($member_authority_result['term'] != 0){
        $data['validity_time'] = strtotime('+'.$member_authority_result['term'].' month');
    }else{
        $data['validity_time'] = 0;
    }

    db('member')->where(array('id'=>$uid))->update($data);
}

/*用于判断用户查阅浏览下载是否有权利，并返回数据，
传入参数:
    user_id，
    分类（project，formula，circular，policy,enterprise_follow_num，wechat_tweets_num，policy_interpretation_num，tracking_bulletin_num，enterprise_planning_num，business_doctor，information_maintenance）
    action（consult，enclosure，down）
返回：bool
**/
function member_right_num($uid, $type, $action='',$is_select='true'){
    //去的参数，判断参数
    if(empty($uid))return false;
    $member_result = db('member')->where(array('id'=>$uid))->find();#用户数据
    $num = unserialize($member_result['num']); #用户 权限数据
    $type_array = [];

    //判断该会员是否过期
    if(time() > $member_result['validity_time'] && $member_result['validity_time'] != '0')return array('bool'=>false);

    if(!$is_select){
        //显示条数,不更新查询次数
        $type_array[] = 'project';
        $type_array[] = 'formula_consult';
        $type_array[] = 'formula_down';
        $type_array[] = 'circular_consult';
        $type_array[] = 'circular_down';
        $type_array[] = 'policy_consult';
        $type_array[] = 'policy_down';
    }

    if(empty($num))return false;
    if(!isset($type)) return false;

    if($action != ''){
        //1：有限制条件 0无限制
        if($num[$type]['is_condition'] == '1')
        {
            //1:可查阅   -1：不可查阅
            if($num[$type][$type.'_'.$action]['is_'.$action.''] == '1')
            {
                //-1:有限 ；1：无限
                if($num[$type][$type.'_'.$action]['is_infinite'] == '-1')
                {
                    //num：可查询次数减一并返回true；
                    if($num[$type][$type.'_'.$action]['num'])
                    {
                        if($num[$type][$type.'_'.$action]['num'] != 0){
                            if(!in_array($type.'_'.$action, $type_array)){
                                $num[$type][$type.'_'.$action]['num'] = $num[$type][$type.'_'.$action]['num'] - 1;
                                $update_num = serialize($num);
                                $result = db('member')->where('id',$uid)->setField('num',$update_num);
                            }

                            return array('bool'=>true,'num'=>$num[$type][$type.'_'.$action]['num'],'is_infinite'=>'-1');
                        }else{
                            return array('bool'=>false,'num'=>$num[$type][$type.'_'.$action]['num'],'is_infinite'=>'-1');
                        }
                    }else{
                        return array('bool'=>false,'num'=>$num[$type][$type.'_'.$action]['num'],'is_infinite'=>'-1');
                    }
                }else{
                    return array('bool'=>true,'num'=>$num[$type][$type.'_'.$action]['num'],'is_infinite'=>'1');
                }
            }else{
                return array('bool'=>false,'num'=>$num[$type][$type.'_'.$action]['num'],'is_infinite'=>$num[$type][$type.'_consult']['is_infinite']);
            }
        }else{
            return array('bool'=>true,'num'=>'0','is_infinite'=>'1');
        }
    }else{
        //1：有限条件
        if($num[$type]['is_condition'] == '1')
        {
            //-1:有限 1：无限
            if($num[$type]['is_infinite'] == '-1')
            {
                if($num[$type]['num'] != 0){
                    if(!in_array($type, $type_array)){
                        $num[$type]['num'] = $num[$type]['num'] - 1;
                        $update_num = serialize($num);
                        $result = db('member')->where('id',$uid)->setField('num',$update_num);
                    }

                    return array('bool'=>true,'num'=>$num[$type]['num'],'is_infinite'=>'-1');

                }else{
                    return array('bool'=>false,'num'=>$num[$type]['num'],'is_infinite'=>'-1');
                }
            }else{
                return array('bool'=>true,'num'=>$num[$type]['num'],'is_infinite'=>'1');
            }
        }else{
            return array('bool'=>false,'num'=>$num[$type]['num'],'is_infinite'=>$num[$type]['is_infinite']);
        }
    }
}

/*    记录套餐修改日志
      传入参数：数组
*/
function member_authority_log($data, $res)
{
//        1.记录操作方式，操作人（付款还是管理员更改）付款成功后记录  付款是否成功（成功：记录）
    if(!in_array($data)) return false;
    if(empty($data)) return false;

    $data = db('authority_log')->insert($data);
    if(!empty($data))
    {
        //返回id
        $id = db('authority_log')->insertGetId();
    }
//        2.记录修改前的数据 与 修改后的数据 ，时间
    if(!in_array($res)) return false;
    if(empty($data)) return false;

    $data = db('authority_log')->where('id', $id)->update($data);
    if(!empty($data))
    {
        return true;
    }else{
        return false;
    }
}

//    获取省
function getProvince(){
    $data = db('area')->where('parent_id',0)->select();
    return $data;
}

//    ajax获取area
function getAreas($id){
    if($id){
        $data = db('area')->where('parent_id',$id)->select();
        $msg = '';
        foreach ($data as $key => $val) {
            $msg .= '<option value="'.$val['id'].'">'.$val['name'].'</option>';
        }
    }
    return $msg;
}

//    获取国家
function getState(){
    $data = db('state')->select();
    return $data;
}

// 查询对应栏的文章
function get_article($name, $file="*", $limit){
    $dynamic_category_result = db('dynamic_category')->where(array('category_name'=>$name))->field('id')->select();

    $dynamic_category_result = array_column($dynamic_category_result, 'id');
    if(empty($dynamic_category_result))return false;

    $where['category'] = array('in', $dynamic_category_result);
    $where['is_display'] = 1;
     
    if(isset($limit)){
        $dynamic = db('dynamic')->where($where)->field($file)->limit($limit)->order('order_by desc')->select();
    }else{
        $dynamic = db('dynamic')->where($where)->field($file)->order('order_by desc')->select();
    }

    return $dynamic;
}
